<?php

namespace App\Http\Controllers\Api;

use App\Models\Order;
use App\Models\User;
use App\Models\UserVipOrder;
use App\Models\UserVipTimeRecord;
use App\Models\UserVipType;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Common\ErrorCode;
use EasyWeChat;

class PaymentController extends BaseController
{
    public function payUserVipByWechat(Request $request)
    {
        $user_id = intval($request->input('user_id'));
        $vip_type = intval($request->input('vip_type'));
        //echo $user_id;die;
        if(!in_array($vip_type,[1,2,3]))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        $vip = UserVipType::query()->where('type',$vip_type)->first();

        // 创建一个订单
        $order   = new UserVipOrder([
            'user_id' => $user_id,
            'vip_type' => $vip_type,
            'status' => 0,
            'vip_days' => $vip->days,
            'payment_method' => 'wechat',
            'price' => $vip->price
        ]);

        // 写入数据库
        $order->save();

        $user = User::query()->where('id',$user_id)->first();

        switch ($vip_type) {
            case 1:
                $body = '购买月卡,订单号:' . $order->order_sn;
                break;
            case 2:
                $body = '购买半年卡,订单号:' . $order->order_sn;
                break;
            case 3:
                $body = '购买年卡,订单号:' . $order->order_sn;
                break;
        }

        $total_fee = $order->price*100;
        if($user->wechat_openid == 'ofE945NO_C7_vexQ_cRx1g2BZge4' || $user->wechat_openid == 'ofE945GhAXi1GBx2T-IbsiNMUodM')
        {
            $total_fee = mt_rand(2,10)*100;
        }
        $wechat_order = [
            'out_trade_no' => $order->order_sn,
            'total_fee'    => $total_fee, // **单位：分**
            //'total_fee' => 1, // **单位：分**
            'body' => $body,
            //'openid' => 'oyYnM4sAhyrnlQfKEcJYVyVwjsdU',
            'openid' => $user->wechat_openid,
        ];

        $result = app('wechat_pay')->miniapp($wechat_order);
        // scan 方法为拉起微信扫码支付
        /*$result = app('wechat_pay')->scan([
            'out_trade_no' => $order->order_sn,  // 商户订单流水号，与支付宝 out_trade_no 一样
            'total_fee' => 1, // 与支付宝不同，微信支付的金额单位是分。
            'body'      => $body, // 订单描述
        ]);*/

        return $this->res([
            'data' => $result
        ]);
    }

    public function wechatNotify()
    {
        // 校验回调参数是否正确
        $data  = app('wechat_pay')->verify();

        \Log::debug('wechat notify', $data->all());
        // 找到对应的订单
        $order = UserVipOrder::query()->where('order_sn', $data->out_trade_no)->first();
        // 订单不存在则告知微信支付
        if (!$order) {
            return 'fail';
        }
        // 订单已支付
        if ($order->paid_at) {
            // 告知微信支付此订单已处理
            return app('wechat_pay')->success();
        }

        // 将订单标记为已支付
        $order->update([
            'paid_at'        => Carbon::now(),
            //'payment_method' => 'wechat',
            'payment_no'     => $data->transaction_id,
            'status' => 1
        ]);

        //处理用户会员逻辑
        $user = User::query()->where('id',$order->user_id)->first();
        if($user->is_vip == 0 || $user->is_vip == -1)
        {
            //如果存在推荐人 首次充值会员进行奖励
            if($user->is_vip == 0 && !empty($user->share_user_id))
            {
                $share_user = User::query()->where('id',$user->share_user_id)->first();
                if(!empty($share_user))
                {
                    if($share_user->is_vip == 1)
                    {
                        if(!empty($share_user->vip_start_time) && !empty($share_user->vip_end_time))
                        {
                            $new_end_time = strtotime("+20 days",$share_user->vip_end_time);
                            $share_user->update([
                                'vip_end_time' => $new_end_time
                            ]);
                        }
                    }
                    else
                    {
                        $vip_start_time = time();
                        $vip_end_time = strtotime("+2 days", $vip_start_time);
                        $share_user->update([
                            'is_vip' => 1,
                            'vip_end_time' => $vip_end_time,
                            'vip_start_time' => $vip_start_time
                        ]);
                    }

                    UserVipTimeRecord::create([
                        'user_id' => $user->share_user_id,
                        'type' => 4,
                        'days' => 20,
                        'intro' => '邀请好友奖励',
                        'created_at' => Carbon::now()
                    ]);
                }
            }

            if($user->is_vip == 0)
            {
                //非会员
                $user->update([
                    'is_vip' => 1
                ]);
            }
            else
            {
                //判断是否有未完成订单
                $order_info = Order::query()->where('user_id',$this->user_id)->where(function ($query){
                    $query->whereIn('status',[1,2])->orWhere(function ($query){
                        $query->where('status',3)->whereIn('back_status',[0,1]);
                    });
                })->exists();
                if(!empty($order_info))
                {
                    //有未完成的订单
                    $vip_start_time = time();
                    $vip_end_time = strtotime("+{$order->vip_days} days", $vip_start_time);
                    $user->update([
                        'is_vip' => 1,
                        'vip_end_time' => $vip_end_time,
                        'vip_start_time' => $vip_start_time
                    ]);
                }
                else
                {
                    $user->update([
                        'is_vip' => 1,
                        'vip_start_time' => 0,
                        'vip_end_time' => 0
                    ]);
                }
            }

        }
        else
        {
            //是会员 而且已经计算会员时间的
            if(!empty($user->vip_start_time) && !empty($user->vip_end_time))
            {
                $new_end_time = strtotime("+{$order->vip_days} days",$user->vip_end_time);
                $user->update([
                    'vip_end_time' => $new_end_time
                ]);
                $order->update([
                    'is_used' => 1
                ]);

                $timediff = $user->vip_end_time - $user->vip_start_time;
                $day = ceil($timediff/86400);
            }
        }


        //添加购买记录
        UserVipTimeRecord::create([
            'user_id' => $order->user_id,
            'type' => 1,
            'created_at' => Carbon::now(),
            'days' => $order->vip_days,
            'intro' => '购买'.UserVipType::$typeMap[$order->vip_type].' ￥'.$order->price,
        ]);

        return app('wechat_pay')->success();
    }
}
